package cn.wokoba.trigger.job;


import cn.wokoba.dao.event.EventPublisher;
import cn.wokoba.service.task.TaskService;
import cn.wokoba.service.task.model.TaskEntity;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

//发送MQ消息任务队列
@Slf4j
@Component()
public class SendMessageTaskJob {
    @Autowired
    TaskService taskService;
    @Autowired
    EventPublisher eventPublisher;


    //    @Scheduled(cron = "0/20 * * * * ?")
    @XxlJob("SendMessageTaskJob")
    public void exec_db0() {
        try {
            // 查询未发送的任务
            List<TaskEntity> taskEntities = taskService.queryNoSendMessageTaskList();
            if (taskEntities.isEmpty()) return;
            // 发送MQ消息
            for (TaskEntity taskEntity : taskEntities) {
                try {
                    eventPublisher.publish(taskEntity.getTopic(), taskEntity.getMessage());
                    taskService.updateTaskSendMessageCompleted(taskEntity.getUserId(), taskEntity.getMessageId());
                } catch (Exception e) {
                    log.error("定时任务，发送MQ消息失败 userId: {} topic: {}", taskEntity.getUserId(), taskEntity.getTopic());
                    taskService.updateTaskSendMessageFail(taskEntity.getUserId(), taskEntity.getMessageId());
                }
            }
        } catch (Exception e) {
            log.error("定时任务，扫描MQ任务表发送消息失败。", e);
        }
    }


}
